package cn.lee.test.common.base.service;

import cn.lee.test.common.base.model.CurdModel;
import cn.lee.test.common.base.repository.MyBaseJpaRepository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author : lichl(李承霖)
 * create: 2021/4/15 11:10
 */
public abstract class MyBaseJpaService<T extends CurdModel<ID>, ID> implements Service<T, ID>{
  protected abstract MyBaseJpaRepository<T, ID> getRepository();
  

  
  // 初始化实体更新时的时间戳
  protected void initEntityUpdate(T entity){
    entity.setUpdatedAt(System.currentTimeMillis());
  }
  
  // 初始化实体的所有默认参数
  protected void initEntityCommon(T entity){
    // 初始化实体创建时的时间戳
    entity.setCreatedAt(System.currentTimeMillis());
    initEntityUpdate(entity);
  }
  
  @Override
  public long curd_countAll(){
    return getRepository().count();
  }
  
  @Override
  @Transactional
  public T curd_create(T entity){
    initEntityCommon(entity);
    return getRepository().save(entity);
  }
  
  @Override
  @Transactional
  public T curd_update(T entity){
    initEntityUpdate(entity);
    return getRepository().save(entity);
  }
  
  @Override
  public T curd_readById(ID id){
//    return getRepository().curd_readById(id);
    return getRepository().findById(id).orElse(null);
  }
  
  @Override
  @Transactional
  public T curd_removeById(ID id){
    T entity = curd_readById(id); // 先查询,获取实体引用
    getRepository().deleteById(id); // 将删除操作持久化,此时实体引用还可以通过内存地址找到.
    return entity;
  }
  
  @Override
  @Transactional
  public T curd_remove(T entity){
    getRepository().delete(entity);
    return entity;
  }
  
  @Override
  public List<T> curd_getAll(){
    return getRepository().findAll();
  }
  
}
